/**
 * 
 */
package com.cqan.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @Description 服务启动是自动开始LISTENER
 * @author slaton.wu@gmail.com
 * @date 2012-7-27上午9:56:56
 *
 */
@Component
@SuppressWarnings("rawtypes")
public  class AppListener implements ApplicationListener,
ApplicationContextAware{
	
	private static final Logger logger = LoggerFactory.getLogger("ds.debug");
	
	private AbstractApplicationContext ctx;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		if (applicationContext instanceof AbstractApplicationContext) {
			ctx = (AbstractApplicationContext) applicationContext;
			ctx.addApplicationListener(this);
		}
	}

	
	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (ctx == null) {
			return;
		}
		boolean doIt = false;
		ApplicationContext ac = ctx;
		while (ac != null && !doIt) {
			if (event.getSource() == ac) {
				doIt = true;
			}
			ac = ac.getParent();
		}
		if (doIt) {
			if (event instanceof ContextRefreshedEvent) {
				//执行业务
				logger.debug("Listener is start....");
			}
		}
	}

}
